package com.christina.engine.state.impl;

import com.christina.engine.state.AbstractConversationState;
import com.christina.engine.state.ConversationState;
import com.christina.engine.state.model.StateContext;
import com.christina.engine.state.model.StateTransitionResult;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 信息收集状态
 * 负责收集用户提供的详细信息
 *
 * @author Christina
 */
@Component
public class InformationGatheringState extends AbstractConversationState {

    public static final String STATE_NAME = "InformationGathering";

    public InformationGatheringState() {
        super(STATE_NAME, StateType.INFORMATION_GATHERING, 180000); // 3分钟超时
    }

    @Override
    protected StateTransitionResult doOnEnter(StateContext context) {
        // 初始化信息收集
        context.setStateData("collectedInfo", new java.util.HashMap<String, Object>());
        context.setStateData("currentQuestion", 0);

        String targetService = context.getStateData("targetService", "chat");
        List<String> questions = getQuestionsForService(targetService);
        context.setStateData("questions", questions);

        if (!questions.isEmpty()) {
            return StateTransitionResult.waitForUserInput(questions.getFirst());
        } else {
            // 没有问题需要询问，直接转到处理状态
            return StateTransitionResult.success(
                    getProcessingState(),
                    "信息收集完成，开始处理您的请求。"
            );
        }
    }

    @Override
    protected StateTransitionResult doHandleMessage(String message, StateContext context) {
        // 验证输入
        ValidationResult validation = validateInput(message, context);
        if (!validation.isValid()) {
            return StateTransitionResult.stayInCurrentState(validation.getErrorMessage());
        }

        // 处理取消命令
        if (isCancelCommand(message)) {
            return StateTransitionResult.success(
                    getInitialState(),
                    "已取消信息收集。还有其他需要帮助的吗？"
            );
        }

        // 处理帮助命令
        if (isHelpCommand(message)) {
            return StateTransitionResult.stayInCurrentState(getHelpMessage(context));
        }

        // 收集当前问题的答案
        int currentQuestion = context.getStateData("currentQuestion", 0);
        @SuppressWarnings("unchecked")
        List<String> questions = (List<String>) context.getStateData("questions", null);
        @SuppressWarnings("unchecked")
        Map<String, Object> collectedInfo = (Map<String, Object>) context.getStateData("collectedInfo", null);

        // 验证并保存答案
        String questionKey = getQuestionKey(currentQuestion, context);
        ValidationResult answerValidation = validateAnswer(questionKey, message, context);

        if (!answerValidation.isValid()) {
            return StateTransitionResult.stayInCurrentState(
                    answerValidation.getErrorMessage() + "\n\n" + questions.get(currentQuestion)
            );
        }

        // 保存答案
        collectedInfo.put(questionKey, message);

        // 检查是否还有更多问题
        int nextQuestion = currentQuestion + 1;
        if (nextQuestion < questions.size()) {
            context.setStateData("currentQuestion", nextQuestion);
            return StateTransitionResult.waitForUserInput(questions.get(nextQuestion));
        } else {
            // 所有信息收集完成，转到处理状态
            return StateTransitionResult.success(
                    getProcessingState(),
                    "信息收集完成，正在为您处理请求..."
            );
        }
    }

    @Override
    protected String getHelpMessage(StateContext context) {
        int currentQuestion = context.getStateData("currentQuestion", 0);
        @SuppressWarnings("unchecked")
        List<String> questions = (List<String>) context.getStateData("questions", null);

        String baseHelp = super.getHelpMessage(context);

        if (questions != null && currentQuestion < questions.size()) {
            return baseHelp + "\n\n当前问题：" + questions.get(currentQuestion) +
                    "\n\n请提供相关信息，或输入 '跳过' 来跳过当前问题。";
        }

        return baseHelp;
    }

    @Override
    public List<ConversationState> getPossibleNextStates(StateContext context) {
        return Arrays.asList(
                getProcessingState(),
                getInitialState(),
                getCompletedState()
        );
    }

    /**
     * 根据服务类型获取问题列表
     *
     * @param targetService 目标服务
     * @return 问题列表
     */
    private List<String> getQuestionsForService(String targetService) {
        return switch (targetService) {
            case "travel" -> Arrays.asList(
                    "请告诉我您的出发地？",
                    "请告诉我您的目的地？",
                    "您计划什么时候出发？（格式：YYYY-MM-DD HH:MM）",
                    "有多少位乘客？",
                    "您偏好的交通方式是什么？（飞机/火车/汽车/不限）"
            );
            case "user" -> Arrays.asList(
                    "您想要修改哪项设置？（语言/主题/通知/偏好）",
                    "请提供新的设置值？"
            );
            default -> List.of(
                    "请详细描述您的问题或需求？"
            );
        };
    }

    /**
     * 获取问题对应的键名
     *
     * @param questionIndex 问题索引
     * @param context 状态上下文
     * @return 问题键名
     */
    private String getQuestionKey(int questionIndex, StateContext context) {
        String targetService = context.getStateData("targetService", "chat");

        return switch (targetService) {
            case "travel" -> switch (questionIndex) {
                case 0 -> "origin";
                case 1 -> "destination";
                case 2 -> "departureTime";
                case 3 -> "passengerCount";
                case 4 -> "transportMode";
                default -> "question_" + questionIndex;
            };
            case "user" -> switch (questionIndex) {
                case 0 -> "settingType";
                case 1 -> "settingValue";
                default -> "question_" + questionIndex;
            };
            default -> "question_" + questionIndex;
        };
    }

    /**
     * 验证用户答案
     *
     * @param questionKey 问题键名
     * @param answer 用户答案
     * @param context 状态上下文
     * @return 验证结果
     */
    private ValidationResult validateAnswer(String questionKey, String answer, StateContext context) {
        // 检查跳过命令
        if (answer.trim().equals("跳过") || answer.trim().equalsIgnoreCase("skip")) {
            return ValidationResult.valid();
        }

        switch (questionKey) {
            case "origin":
            case "destination":
                if (answer.trim().length() < 2) {
                    return ValidationResult.invalid("地点名称至少需要2个字符");
                }
                break;

            case "departureTime":
                if (!isValidDateTime(answer)) {
                    return ValidationResult.invalid("请输入有效的日期时间格式（YYYY-MM-DD HH:MM）");
                }
                break;

            case "passengerCount":
                try {
                    int count = Integer.parseInt(answer.trim());
                    if (count < 1 || count > 20) {
                        return ValidationResult.invalid("乘客数量必须在1-20之间");
                    }
                } catch (NumberFormatException e) {
                    return ValidationResult.invalid("请输入有效的数字");
                }
                break;

            case "transportMode":
                if (!Arrays.asList("飞机", "火车", "汽车", "高铁", "不限").contains(answer.trim())) {
                    return ValidationResult.invalid("请选择有效的交通方式：飞机/火车/汽车/高铁/不限");
                }
                break;

            case "settingType":
                if (!Arrays.asList("语言", "主题", "通知", "偏好").contains(answer.trim())) {
                    return ValidationResult.invalid("请选择有效的设置类型：语言/主题/通知/偏好");
                }
                break;
        }

        return ValidationResult.valid();
    }

    /**
     * 验证日期时间格式
     *
     * @param dateTimeStr 日期时间字符串
     * @return 是否有效
     */
    private boolean isValidDateTime(String dateTimeStr) {
        try {
            java.time.LocalDateTime.parse(dateTimeStr.replace(" ", "T"));
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    private ConversationState getProcessingState() {
        return new ProcessingState();
    }

    private ConversationState getInitialState() {
        return new InitialState();
    }

    private ConversationState getCompletedState() {
        return new CompletedState();
    }
}
